<?php

namespace App\Http\Controllers;

use App\Http\Requests\AgentStoreRequest;
use App\Http\Requests\AgentUpdateRequest;
use App\Models\Agent;
use App\Services\AgentCashService;
use Illuminate\Http\Request;

class AgentController extends Controller
{
    /**
     * 后台首页
     */
    public function index() {
        return view("agent.index");
    }
    /**
     * 客户列表api
     */
    public function list(Request $request) {
        $name=$realname=$username=$address=$agent_level_id=$mob=$balance_min=$balance_max=$dateStart=$dateEnd=null;
        $para = $request->post('params');

        //组装查询条件
        if (is_array($para)) {
            $name = $para['name'];
            $agent_level_id = $para['agent_level_id'];
            $realname = $para['realname'];
            $username = $para['username'] ?? null;
            $address = $para['address'] ?? null;
            $mob = $para['mob'] ?? null;
            $balance_min = $para['balance_min'] ?? null;
            $balance_max = $para['balance_max'] ?? null;
            if (isset($para['range_date']) && !empty($para['range_date'])) {
                $tmp = explode('~', $para['range_date']);
                $dateStart = strtotime(trim($tmp[0]));
                $dateEnd = strtotime(trim($tmp[1]));
            }
        }

        $limit = empty($request->get('limit')) ? 15 : $request->get('limit');
        $agent = Agent::when($name, function ($query, $name) {
                    return $query->where('name', 'like', '%'.$name.'%');
                })
                ->when($agent_level_id, function ($query, $agent_level_id) {
                    return $query->where('agent_level_id', '=', $agent_level_id);
                })
                ->when($realname, function ($query, $realname) {
                    return $query->where('realname', 'like', '%'.$realname.'%');
                })
                ->when($username, function ($query, $username) {
                    return $query->where('username', 'like', '%'.$username.'%');
                })
                ->when($address, function ($query, $address) {
                    return $query->where('address', 'like', '%'.$address.'%');
                })
                ->when($mob, function ($query, $mob) {
                    return $query->where('mob', 'like', '%'.$mob.'%');
                })
                ->when(($balance_min && $balance_max), function ($query) use($balance_min, $balance_max){
                    return $query->whereBetween('cash', [$balance_min*100, $balance_max*100]);
                })
                ->when(($dateStart && $dateEnd), function ($query) use($dateStart, $dateEnd){
                    return $query->whereBetween('created_at', [$dateStart, $dateEnd]);
                })
                ->orderByDesc('id')
                ->paginate($limit);

        return $agent;
    }
    /**
     * 删除客户api
     */
    public function delete(Request $request) {
        $idStr = $request->get('id');
        return $idStr;
    }
    /**
     * 新建客户
     */
    public function create() {
        return view('agent.create');
    }
    /**
     * 保存客户api
     */
    public function store(AgentStoreRequest $request) {
        $para = $request->except('_token');
        $para['password'] = bcrypt($para['password']);
        $agent = new Agent($para);
        $result = $agent->save();
        if (!$result) {
            return $this->toJSON(1001, '操作失败，请稍后再试');
        }
        return $this->toJSON(200);
    }
    /**
     * 编辑客户
     */
    public function edit(Request $request) {
        $id = (int)$request->get('id');
        $data = Agent::find($id);
        return view('agent.edit', $data);
    }
    /**
     * 更新客户api
     */
    public function update(AgentUpdateRequest $request) {
        $id = $request->input('id');
        $password = $request->input('password');
        $agent = Agent::find($id);
        $agent->mob = $request->input('name');
        $agent->agent_level_id = $request->input('agent_level_id');
        $agent->realname = $request->input('realname');
        $agent->mob = $request->input('mob');
        $agent->province = $request->input('province');
        $agent->city = $request->input('city');
        $agent->country = $request->input('country');
        $agent->address = $request->input('address');
        if (!empty($password)) {
            $agent->password = bcrypt($password);
        }
        $status = $agent->save();

        if (!$status) {
            return $this->toJSON(1001, '操作失败，请稍后再试');
        }
        return $this->toJSON(200);
    }
    /**
     * 账户充值扣款api
     */
    public function recharge(Request $request, AgentCashService $agentCashService) {
        $id = $request->get('id');
        $amount = $request->get('amount');
        if (empty($id)) {
            return $this->toJSON(1002, '非法参数');
        }
        $request->validate([
            'amount' => ['required','regex:/^(\-|\+)?\d+(\.\d+)?$/'],
        ],[
            'amount.required' => '金额必填',
            'amount.regex' => '仅支持正数、负数，小数保留两位',
        ]);
        $amount = intval($amount * pow(10, 2))/ pow(10, 2);
        $code = $amount > 0 ? $agentCashService->recharge($id, $amount, 1) : $agentCashService->recharge($id, $amount, 2);
        switch ($code) {
            case '1001':
                return $this->toJSON(1001, '操作失败，请稍后再试');
                break;
            case '1003':
                return $this->toJSON(1003, '余额不足');
                break;
            default:
                return $this->toJSON(200);
        }
    }

}
